const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const jwtConfig = require('../jwt-config/index')

exports.register = (req, res) => {
  const reqInfo = req.body
  if (!reqInfo.account || !reqInfo.password) {
    return res.reqError('账号或密码不能为空')
  }

  const sql = `select * from users where account = ?`
  db.query(sql, reqInfo.account, (err, results) => {
    if (err) {
      return res.reqError(err)
    }
    if (results.length > 0) {
      return res.reqError('账号已存在')
    }
    reqInfo.password = bcrypt.hashSync(reqInfo.password, 10)
    const sql1 = 'insert into users set ?'
    const identity = '用户'
    const createTime = new Date()
    db.query(
      sql1,
      {
        account: reqInfo.account,
        password: reqInfo.password,
        identity,
        createTime,
        status: 0,
      },
      (err, results) => {
        if (err) {
          return res.reqError(err)
        }
        if (results.affectedRows !== 1) {
          return res.reqError('注册账号失败')
        }
        res.send({
          status: '200',
          message: '注册成功',
        })
      },
    )
  })
}

exports.login = (req, res) => {
  const loginInfo = req.body
  const sql = `select * from users where account = ?`
  db.query(sql, loginInfo.account, (err, result) => {
    if (err) {
      return res.reqError(err)
    }
    if (result.length !== 1) {
      return res.reqError('登录失败！')
    }
    const compareRes = bcrypt.compareSync(loginInfo.password, result[0].password)
    if (!compareRes) {
      return res.reqError('登录失败！')
    }
    if (result[0].status === 1) {
      return res.reqError('账号已冻结！')
    }
    const user = {
      ...result,
      password: '',
      imageUrl: '',
      createTime: '',
      updateTime: '',
    }
    const tokenStr = jwt.sign(user, jwtConfig.jwtSecretKey, {
      expiresIn: '7h',
    })
    res.send({
      status: '200',
      message: '登录成功',
      token: 'Bearer ' + tokenStr,
      result: result[0],
    })
  })
}
